package personal.zq.practice.common.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * 直接用map接收数据
 *
 * @author 尚气(zhao tian hao)
 * @version 1.0
 * @date 2020/3/5 20:14
 */
@Slf4j
public abstract class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final int BATCH_COUNT = 3000;

    protected List<Map<Integer, String>> list = new ArrayList<>();

    protected Map<Integer, String> headNameMap;

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        headNameMap = headMap;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 继承此方法处理数据
     */
    protected void saveData() {
        log.info("{}条数据，自定义方法进行处理！", list.size());
    }
}
